/*

Copyright (c) 2021 唐佐林
WeChat : delphi_tang
EMail: delphi_tang@dt4sw.com

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/
#include "tx_context.h"
#include "app_utils.h"
#include "ipc_message.h"
#include "ipc_msg_const.h"
#include "cmsis_os2.h"
#include "lwip/sockets.h"

#include <string.h> 
#include <malloc.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

#define REMOTE_PORT 9000

static int SendTo(int sock, Message* msg, struct sockaddr_in* addr)
{
    size_t size = sizeof(*msg) + msg->length;
        
    msg->type = htons(msg->type);
    msg->cmd = htons(msg->cmd);
    msg->index = htons(msg->index);
    msg->total = htons(msg->total);
    msg->length = htonl(msg->length);

    return (sendto(sock, msg, size, 0, (struct sockaddr*)addr, sizeof(*addr)) == size) ? 0 : -1;  
}

static void* TX_Context_Task(const char* arg)
{
    int sock = 0;
    struct sockaddr_in remote = {0};

    sock = socket(PF_INET, SOCK_DGRAM, 0);

    if( sock == -1 )
    {
        LastError("Can NOT create TX socket.");
        return NULL;
    }

    remote.sin_family = AF_INET;
    remote.sin_port = htons(REMOTE_PORT);

    while( 1 )
    {
        if( Wifi_IsOk() )
        {
            char* rip = Server_CAddr();

            if( rip )
            {
                Message msg = {IPC_TYPE_STATE, IPC_STATE_SIGNAL, 0, 0, 0};

                int brd = 0;

                remote.sin_addr.s_addr = inet_addr(rip);

                setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &brd, sizeof(brd));

                SendTo(sock, &msg, &remote);
            }
            else
            {
                char* lip = Wifi_IpAddr();

                if( lip )
                {
                    int brd = 1;
                    char buf[sizeof(Message) + 16] = {0};
                    Message* pMsg = (Message*)buf;
                    
                    pMsg->type = IPC_TYPE_STATE;
                    pMsg->cmd = IPC_STATE_HOST;
                    pMsg->index = 0;
                    pMsg->total = 0;
                    pMsg->length = 16;

                    remote.sin_addr.s_addr = (inet_addr(lip) | 0xFF000000);
                    
                    strcpy((char*)pMsg->payload, lip);

                    setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &brd, sizeof(brd));

                    SendTo(sock, pMsg, &remote);
                }
            }
        }

        sleep(1);
    }

    return (void*)arg;
}

void TX_Context_Entry(void)
{
    osThreadAttr_t attr = {0};

    attr.name = "TX Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 5;
    attr.priority = osPriorityNormal;

    if (osThreadNew((osThreadFunc_t)TX_Context_Task, NULL, &attr) == NULL)
    {
        printf("[dt4sw] Falied to create TX task!\n");
    }
}
